//
//  FunnyViewController.m
//  HaHa
//
//  Created by lanou3g on 15/9/18.
//  Copyright (c) 2015年 吉亚平. All rights reserved.
//

#import "FunnyViewController.h"

@interface FunnyViewController ()
{
    NSInteger number;
}
//人气数组
@property (nonatomic,strong) NSMutableArray *modelArray;
//精选数组
@property (nonatomic, strong) NSMutableArray *SelectModelArray;
//GIF数组
@property (nonatomic, strong) NSMutableArray *GifModelArray;

//人气tableView
@property (nonatomic,strong) UITableView *tableView;

@property (nonatomic, strong) UIScrollView *scrollView;
//精选tableView
@property (nonatomic, strong) UITableView *SelectTableView;
//GIFtableView
@property (nonatomic, strong) UITableView *GifTableView;

@property (nonatomic) UIImageView *refreshButton;

@end

@implementation FunnyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    self.navigationController.navigationBar.translucent = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    [self AddSegment];
    [self addScrollView];
    [self addSelectTableView];
    [self AddTableView];
    [self addGifTableView];
    
    [self reloadSentimentAndJson];
    [self reloadSelectAndJson];
    [self reloadGifAndJson];

    [self addrefreshButton];
    
    
    [self mjrefresh];

       [self AddAcTivityView];
    
}


#pragma mark ========上拉加载,下拉刷新=============
- (void)mjrefresh
{
    __block FunnyViewController *root = self;
    [self.tableView addHeaderWithCallback:^{
        [root.tableView headerEndRefreshing];
    }];
    [self.tableView addFooterWithCallback:^{ 
        [root reloadSentimentAndJson];
        [root.tableView footerEndRefreshing];
    }];

    [self.SelectTableView addHeaderWithCallback:^{
        [root.SelectTableView headerEndRefreshing];
    }];
    [self.SelectTableView addFooterWithCallback:^{
        [root reloadSelectAndJson];
        [root.SelectTableView footerEndRefreshing];
    }];
    [self.GifTableView addHeaderWithCallback:^{
        [root.GifTableView headerEndRefreshing];
    }];
    [self.GifTableView addFooterWithCallback:^{
        [root reloadGifAndJson];
        [root.GifTableView footerEndRefreshing];
    }];
    
}
//刷新按钮
-(void)addrefreshButton{
    UIView *Back = [[UIView alloc] initWithFrame:CGRectMake(kScreenWdth-60, kScreenHeight-163, 40, 40)];
    Back.backgroundColor = [UIColor whiteColor];
    Back.layer.borderWidth = 0.5;
    Back.alpha = 0.8;
    Back.layer.borderColor = [[UIColor brownColor] CGColor];
    Back.layer.cornerRadius = 20;
    
    self.refreshButton = [[UIImageView alloc] initWithFrame:CGRectMake(7.5,7.5 , 25, 25)];
    self.refreshButton.image = [UIImage imageNamed:@"16"];
    self.refreshButton.layer.borderColor = [[UIColor brownColor] CGColor];
    self.refreshButton.userInteractionEnabled = YES;
    [self GifData];
    self.refreshButton.animationDuration = 0.4;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(refreshButtonClick)];
    [self.refreshButton addGestureRecognizer:tap];
    [Back addSubview:self.refreshButton];
    [self.view addSubview:Back];
     [self.refreshButton startAnimating];
}

//刷新按钮事件
- (void)refreshButtonClick{
    [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
    [self reloadSentimentAndJson];
}

//gifData
- (void)GifData{
    NSMutableArray *images = [[NSMutableArray alloc] init];
    for (int i = 0; i < 22; i++) {
        UIImage *temp = [UIImage imageNamed:[NSString stringWithFormat:@"%d",i+1]];
        [images addObject:temp];
    }
    self.refreshButton.animationImages = images;
}
#pragma mark ========解析人气数据=============
- (void)reloadSentimentAndJson
{
    [self.refreshButton startAnimating];
    [LORequestManger GET:KPicDayUrl success:^(id response) {
        NSDictionary *dic = (NSDictionary *)response;
        NSDictionary *DataDic = [dic objectForKey:@"data"];
        NSArray *DataArray = [DataDic objectForKey:@"data"];
        if (self.modelArray == nil) {
            self.modelArray = [NSMutableArray array];
        }
        
//        NSLog(@"%@",[DataArray firstObject]);
        for (NSDictionary *temp in DataArray) {
            FunnyModel *funnyModel = [FunnyModel SetModeWithDIC:temp];
            [self.modelArray addObject:funnyModel];

        }
        [self.tableView reloadData];
        [_activity stopAnimating];
        [self animationD];
        [self.refreshButton stopAnimating];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}

#pragma mark ========解析精选数据=============
- (void)reloadSelectAndJson
{
    [self.refreshButton startAnimating];
    number += 20;
    NSString *url = [NSString stringWithFormat:@"%@%ld%@",kSelectPicA,number,kSelectPicB];
    if (_SelectModelArray == nil) {
        _SelectModelArray = [NSMutableArray array];
    }
    [LORequestManger GET:url success:^(id response) {
        NSDictionary *dic = (NSDictionary *)response;
        
        NSDictionary *DataDic = [dic objectForKey:@"data"];
        NSArray *DataArray = [DataDic objectForKey:@"data"];
        int a = 0;
        for (NSDictionary *temp in DataArray) {
            ++a;
            if (a > _SelectModelArray.count) {
            FunnyModel *funnyModel = [FunnyModel SetModeWithDIC:temp];
            [self.SelectModelArray addObject:funnyModel];
            }
        }
        NSLog(@"%lu",(unsigned long)self.SelectModelArray.count);
        [self.SelectTableView reloadData];
        [_activity stopAnimating];
        [self animationD];
        [self.refreshButton stopAnimating];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];

}

#pragma mark ==========gifTableView===========
- (void)reloadGifAndJson
{
    [self.refreshButton startAnimating];
    [LORequestManger GET:kGIFUrl success:^(id response) {
        NSDictionary *dic = (NSDictionary *)response;
        NSDictionary *DataDic = [dic objectForKey:@"data"];
        NSArray *DataArray = [DataDic objectForKey:@"data"];
        if (self.GifModelArray == nil) {
            self.GifModelArray = [NSMutableArray array];
        }
        
        for (NSDictionary *temp in DataArray) {
            
            FunnyModel *GifModel = [FunnyModel SetModeWithDIC:temp];
            [self.GifModelArray addObject:GifModel];
        }
        [self.GifTableView reloadData];
        [_activity stopAnimating];
        [self animationD];
        [self.refreshButton stopAnimating];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}

#pragma mark ==========tableView点击跳转==========
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    FunnyModel *model;
    CommonTableViewController *commonVC = [[CommonTableViewController alloc] init];
    if (tableView == self.tableView) {
        model = [self.modelArray objectAtIndex:indexPath.section];
        commonVC.fModel = model;
    }else if (tableView == self.SelectTableView){
        model = [self.SelectModelArray objectAtIndex:indexPath.section];
        commonVC.fModel = model;
    }else{
        model = [self.GifModelArray objectAtIndex:indexPath.section];
        commonVC.fModel = model;
    }
    
    
    
    
    [self.navigationController pushViewController:commonVC animated:YES];
}



- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
        if (scrollView.contentOffset.y < - 150) {
            [_activity startAnimating];
            [self reloadSentimentAndJson];
            
        }
}

#pragma mark ========减速结束方法=============
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    self.Segment.selectedSegmentIndex = _scrollView.contentOffset.x / kScreenWdth;
}


#pragma mark ======设置第一个tableView=============
- (void)AddTableView
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(5, 0, kScreenWdth - 10, kScreenHeight - 113)];
    _tableView.backgroundColor = [UIColor purpleColor];
    _tableView.delegate = self;
    _tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    _tableView.dataSource = self;
    [self.scrollView addSubview:_tableView];
    
}
#pragma mark ======设置第二个tableView=============
- (void)addSelectTableView
{
    _SelectTableView = [[UITableView alloc] initWithFrame:CGRectMake(5+kScreenWdth, 0, kScreenWdth - 10, kScreenHeight - 113)];
    _SelectTableView.delegate = self;
    _SelectTableView.separatorStyle = UITableViewCellSelectionStyleNone;
    _SelectTableView.dataSource = self;
    [self.scrollView addSubview:_SelectTableView];
}

- (void)addGifTableView
{
    _GifTableView = [[UITableView alloc] initWithFrame:CGRectMake(5+kScreenWdth * 2, 0, kScreenWdth - 10, kScreenHeight - 113)];
    _GifTableView.delegate = self;
    _GifTableView.separatorStyle = UITableViewCellSelectionStyleNone;
    _GifTableView.dataSource = self;
    [self.scrollView addSubview:_GifTableView];}

#pragma mark ======添加segment=============
- (void)AddSegment{
    UIView *title = [[UIView alloc] initWithFrame:CGRectMake(0, 4, kScreenWdth - 20, 30)];
    _Segment = [[UISegmentedControl alloc] initWithItems:@[@"人气",@"精选",@"GIF"]];
    _Segment.frame = title.frame;
    [_Segment addTarget:self action:@selector(segmentClick) forControlEvents:(UIControlEventValueChanged)];
    _Segment.selectedSegmentIndex = 0;
    _Segment.tintColor = [UIColor purpleColor];
    [title addSubview:_Segment];
    self.navigationItem.titleView=title;
    
}
#pragma mark ======segment点击方法=============
- (void)segmentClick
{

    [_scrollView setContentOffset:CGPointMake(self.Segment.selectedSegmentIndex * kScreenWdth, 0) animated:YES];
}

#pragma mark ======添加scrollView=============
- (void)addScrollView
{
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kScreenWdth, kScreenHeight)];
    _scrollView.contentSize = CGSizeMake(kScreenWdth * 3, 0);
    _scrollView.minimumZoomScale = 0.5;
    _scrollView.maximumZoomScale = 3;
    _scrollView.delegate = self;
    _scrollView.pagingEnabled = YES;
    [self.view addSubview:_scrollView];
    
}


#pragma mark ======创建风火轮并添加=============
- (void)AddAcTivityView{
    self.activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    self.activity.alpha = 0.9;
    self.activity.frame = CGRectMake(kScreenWdth/2-40, kScreenHeight/2-90, 80, 80);
    self.activity.layer.cornerRadius = 5;
    self.activity.layer.borderColor = [[UIColor whiteColor] CGColor];
    self.activity.layer.borderWidth = 1;
    [self.activity startAnimating];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 60, 80, 20)];
    label.font = [UIFont boldSystemFontOfSize:11];
    label.text = @"正在加载..";
    label.textAlignment = NSTextAlignmentCenter;
    _activity.backgroundColor = [UIColor grayColor];
    [_activity addSubview:label];
    [self.view addSubview:_activity];
}




//动画
- (void)animationD{
    CATransition *transition = [CATransition animation];
    //指定动画类型
    transition.type = @"rippleEffect";//效果类型
    transition.subtype = kCATransitionFromTop;//方向类型 决定动画的开始方向
    transition.duration = 0.8; //单次动画时长
    [self.view.superview.layer addAnimation:transition forKey:@" 但是"];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (tableView == self.tableView) {
        return self.modelArray.count;
    }else if(tableView == self.SelectTableView){
        return self.SelectModelArray.count;
    }else{
        return self.GifModelArray.count;
    }
        return self.modelArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

#pragma mark ==========返回indexPath返回行的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    FunnyModel *model;
    if (tableView == self.tableView) {
        model = self.modelArray[indexPath.section];
    }else if(tableView == self.SelectTableView){
        model = self.SelectModelArray[indexPath.section];
    }else{
        model = self.GifModelArray[indexPath.section];
    }
    
    NSString *widthTemp = [model.large_image objectForKey:@"width"];
    NSString *imagehieghtTemp = [model.large_image objectForKey:@"height"];
    NSInteger width = [widthTemp integerValue];
    NSInteger height = [imagehieghtTemp integerValue];
    //如果大于表视图的宽度 等比缩放到与表视图等宽
    CGFloat imageHeight;
    if (width>tableView.width) {
        CGFloat beishu = width/tableView.width;
        imageHeight = height/beishu;
    }else if(height == 0){
        imageHeight = tableView.width;
    }else{
        imageHeight = height;
    }
    //图片标题高度
    CGFloat Textheight = [self YYHreturnStringHeight:model.text Width:kScreenWdth-20 Font:17];
    //评论内容高度
    NSDictionary *tempDic = [model.comments firstObject];
    NSString *CommentText = [tempDic objectForKey:@"text"];
    CGFloat CommentTextheight = [self YYHreturnStringHeight:CommentText Width:kScreenWdth-20 Font:17];
    
    if (model.comments.count == 0) {
        return 150 - 70 +Textheight+imageHeight ;
        
    }
    
    return 112+Textheight+imageHeight+CommentTextheight + 100;
}

#pragma mark ==========表头==========
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"myCell";
    FunnyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[FunnyTableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifier];
    }
    
    
    if (tableView == self.tableView) {
    FunnyModel *model = self.modelArray[indexPath.section];
    [cell setValueWithModel:model];
    }else if(tableView == self.SelectTableView)
    {
      FunnyModel *model = self.SelectModelArray[indexPath.section];
      [cell setValueWithModel:model];
        
    }else{
        FunnyModel *model = self.GifModelArray[indexPath.section];
        [cell setValueWithModel:model];
    }
    
    return cell;
}

//segment跳转


- (CGFloat)YYHreturnStringHeight:(NSString *)string Width:(CGFloat)Width Font:(int)font{
    
    CGRect frame = [string boundingRectWithSize:CGSizeMake(Width, 10000) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:font] forKey:NSFontAttributeName] context:nil];
    
    return frame.size.height;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
